import { host as h5Host, imgHost as h5ImgHost } from '@/config/h5';
import { host as mpWeixinHost, imgHost as mpWeixinImgHost } from '@/config/mp-weixin';
// #ifdef H5
import { wxGetLocation, wxOpenLocation } from '@/utils/h5/wxLocation.js';
// #endif


/**
 * @description 根据打包平台获取对应配置的域名
 */
export const getHost = function() {
	let host, imgHost;

	// #ifdef H5
	host = h5Host;
	imgHost = h5ImgHost;
	// #endif

	// #ifdef MP-WEIXIN
	host = mpWeixinHost;
	imgHost = mpWeixinImgHost;
	// #endif

	return {
		host,
		imgHost,
	};
}


/** 
 * @description 判断一个数组是否全部包含target数组
 * */
export const isAllIncludes = (target, reference) => {
	return target.every(item => {
		return reference.includes(item)
	})
}

/**
 * @description 防抖 
 * */
export const debounce = function(func, delay = 300) {
	let timer;
	return function() {
		let context = this;
		let args = arguments;
		clearTimeout(timer);
		timer = setTimeout(function() {
			func.apply(context, args);
		}, delay);
	};
};

/**
 * @description 深拷贝 
 * */
export const deepClone = function(data) {
	//string,number,bool,null,undefined,symbol,object,array,date
	if (data && typeof data === 'object') {
		//针对函数的拷贝
		if (typeof data === 'function') {
			let tempFunc = data.bind(null);
			tempFunc.prototype = deepClone(data.prototype);
			return tempFunc;
		}

		switch (Object.prototype.toString.call(data)) {
			case '[object String]':
				return data.toString();
			case '[object Number]':
				return Number(data.toString());
			case '[object Boolean]':
				return new Boolean(data.toString());
			case '[object Date]':
				return new Date(data.getTime());
			case '[object Array]':
				var arr = [];
				for (let i = 0; i < data.length; i++) {
					arr[i] = deepClone(data[i]);
				}
				return arr;

				//js自带对象或用户自定义类实例
			case '[object Object]':
				var obj = {};
				for (let key in data) {
					//会遍历原型链上的属性方法，可以用hasOwnProperty来控制 （obj.hasOwnProperty(prop)
					obj[key] = deepClone(data[key]);
				}
				return obj;
		}
	} else {
		//string,number,bool,null,undefined,symbol
		return data;
	}
};

/**
 * @description 延迟执行
 */
export const delay = function(fn, time = 600) {
	let timeId = setTimeout(() => {
		fn();
		clearTimeout(timeId);
	}, time)
}

/**
 * @description 阻塞执行
 */
export const sleep = function(time = 600) {
	return new Promise(rosolve => {
		let timeId = setTimeout(() => {
			rosolve(true);
			clearTimeout(timeId);
		}, time)
	});
}

/**
 * @description 查询节点
 */
export const queryNode = (context, selector) => {
	return new Promise(resolve => {
		let query = uni.createSelectorQuery().in(context);
		query.select(`${selector}`).boundingClientRect((data) => {
			resolve(data);
		}).exec();
	});
}

/**
 * @description 金额格式化函数 
 * */
export const formatterPrice = function(value) {
	value = value.toString()
	value = value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
	value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
	value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
	value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
	if (value.indexOf(".") < 0 && value != "") { //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
		value = parseFloat(value);
	}
	value = parseFloat(value)

	if (Number.isNaN(value) || value === 0) return ''
	return value.toString()
}


/**
 * @description 获取图片信息 
 * */
export const getImageInfo = (src) => {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src,
			success(res) {
				resolve(res);
			},
			fail(e) {
				console.log(e);
				reject(false);
			}
		})
	})
};

/**
 * @description 复制
 */
export const copy = (res, isToast = true) => {
	// #ifdef H5
	let oInput = document.createElement('input')
	oInput.value = res
	document.body.appendChild(oInput)
	oInput.select() // 选择对象
	document.execCommand('Copy') // 执行浏览器复制命令
	if (isToast) {
		uni.showToast({
			title: "复制成功",
			icon: "none",
		});
	}
	oInput.remove()
	// #endif
	// #ifndef H5
	uni.setClipboardData({
		data: res,
		success: function() {
			if (isToast) {
				uni.showToast({
					title: "复制成功",
					icon: "none",
				});
			}
		},
	});
	// #endif
};

/**
 * hex颜色转rgb颜色
 * @param str 颜色值字符串
 * @returns 返回处理后的颜色值
 */
export function hexToRgb(str) {
	let hexs = "";
	let reg = /^\#?[0-9A-Fa-f]{6}$/;
	if (!reg.test(str)) return ElMessage.warning("输入错误的hex");
	str = str.replace("#", "");
	hexs = str.match(/../g);
	for (let i = 0; i < 3; i++) hexs[i] = parseInt(hexs[i], 16);
	return hexs;
}

/**
 * rgb颜色转Hex颜色
 * @param r 代表红色
 * @param g 代表绿色
 * @param b 代表蓝色
 * @returns 返回处理后的颜色值
 */
export function rgbToHex(r, g, b) {
	let reg = /^\d{1,3}$/;
	if (!reg.test(r) || !reg.test(g) || !reg.test(b)) return uni.showToast({
		title: '输入错误的rgb颜色值'
	});
	let hexs = [r.toString(16), g.toString(16), b.toString(16)];
	for (let i = 0; i < 3; i++)
		if (hexs[i].length == 1) hexs[i] = `0${hexs[i]}`;
	return `#${hexs.join("")}`;
}

/**
 * 加深颜色值
 * @param color 颜色值字符串
 * @param level 加深的程度，限0-1之间
 * @returns 返回处理后的颜色值
 */
export function getDarkColor(color, level) {
	let reg = /^\#?[0-9A-Fa-f]{6}$/;
	if (!reg.test(color)) return uni.showToast({
		title: '输入错误的hex颜色值'
	});
	let rgb = hexToRgb(color);
	for (let i = 0; i < 3; i++) rgb[i] = Math.floor(rgb[i] * (1 - level));
	return rgbToHex(rgb[0], rgb[1], rgb[2]);
}

/**
 * 变浅颜色值
 * @param color 颜色值字符串
 * @param level 变浅的程度，限0-1之间
 * @returns 返回处理后的颜色值
 */
export function getLightColor(color, level) {
	let reg = /^\#?[0-9A-Fa-f]{6}$/;
	if (!reg.test(color)) return uni.showToast({
		title: '输入错误的hex颜色值'
	});
	let rgb = hexToRgb(color);
	for (let i = 0; i < 3; i++) rgb[i] = Math.floor((255 - rgb[i]) * level + rgb[i]);
	return rgbToHex(rgb[0], rgb[1], rgb[2]);
}

/**
 * 获取用户经纬度
 */
export function getLocation(http) {
	return new Promise((resolve, reject) => {

		function getLocationFail(error) {
			const { primaryColor } = useGetThemColor();
			uni.showModal({
				title: '获取位置失败，请检查手机定位权限和微信定位权限开启后重试！',
				showCancel: false,
				confirmColor: primaryColor.value,
			});
			reject(error);
		}

		// #ifdef H5
		const url = window.location.href.split('#')[0];
		http({
			url: '/api/reqwxsdk',
			method: 'POST',
			loadingTip: '处理中',
			data: {
				url,
			}
		}).then(res => {
			wxGetLocation(res, (data) => {
				var latitude = data.latitude; // 纬度，浮点数，范围为90 ~ -90
				var longitude = data.longitude; // 经度，浮点数，范围为180 ~ -180。
				if (latitude == '' || latitude == null || latitude == undefined)
					return getLocationFail(false);
				if (longitude == '' || longitude == null || longitude == undefined)
					return getLocationFail(false);

				resolve({ latitude, longitude });
			}, error => {
				getLocationFail(error);
			})
		})
		// #endif

	})
}

/**
 * 打开地图查看位置
 */
export function openLocation(http, positionInfo) {
	function openLocationFail(tip = '打开地图失败') {
		const { primaryColor } = useGetThemColor();
		uni.showModal({
			title: tip,
			showCancel: false,
			confirmColor: primaryColor.value,
		});
	}

	// #ifdef H5
	const url = window.location.href.split('#')[0];
	http({
		url: '/api/reqwxsdk',
		method: 'POST',
		loadingTip: '处理中',
		data: {
			url,
		}
	}).then(res => {
		wxOpenLocation(res, positionInfo, null, () => {
			openLocationFail('打开地图失败，请升级微信版本后重试')
		})
	})
	// #endif
}